package com.tvunetworks.center.device.controller;

import com.tvunetworks.center.common.constant.LocalConstant;
import com.tvunetworks.center.common.model.LoginUser;
import com.tvunetworks.center.common.model.SearchDeviceParam;
import com.tvunetworks.center.common.model.UserBehavior;
import com.tvunetworks.center.common.model.UserCondition;
import com.tvunetworks.center.common.util.JsonUtil;
import com.tvunetworks.center.common.util.MyUtil;
import com.tvunetworks.center.common.util.Result;
import com.tvunetworks.center.common.util.ResultUtil;
import com.tvunetworks.center.device.annotation.Logined;
import com.tvunetworks.center.device.model.json.PageParam;
import com.tvunetworks.center.device.service.UserBehaviorService;
import com.tvunetworks.center.device.service.UserConditionService;
import com.tvunetworks.center.device.service.UserDeviceService;
import com.tvunetworks.center.device.service.feign.UserFeignService;
import com.tvunetworks.center.device.util.PageBar;
import com.tvunetworks.center.device.util.RedisUtil;
import com.tvunetworks.center.gs.model.Device;
import com.tvunetworks.center.gs.model.DeviceExtend;
import com.tvunetworks.center.gs.model.UserDeviceOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: tvucc-aggregator
 * @description: UserDeviceController
 * @author lebronchen
 * @create: 2019-08-01 15:26
 **/
@Slf4j
@RestController
@RequestMapping("/userDevice")
public class UserDeviceController {

    @Autowired
    private UserDeviceService userDeviceService;
    @Autowired
    private UserConditionService userConditionService;
    @Autowired
    private UserBehaviorService userBehaviorService;
    @Autowired
    private UserFeignService userFeignService;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * @param loginUser loginUser
     * @param param     param
     * @param request   request
     * @return Result
     */
    @GetMapping("/listRPSDevice")
    public Result<Object> listRPSDevice(@Logined LoginUser loginUser, SearchDeviceParam param, HttpServletRequest request) {
        if (loginUser == null) {
            String accessToken = request.getHeader(LocalConstant.ACCESS_TOKEN_KEY);
            if (StringUtils.isEmpty(accessToken)) {
                return ResultUtil.noLogin();
            }
            log.error(" listRPSDevice get session :[{}]",accessToken);
            loginUser = (LoginUser) redisUtil.get(LocalConstant.REDIS_LOGIN_USER_KEY + accessToken);
            if (loginUser == null) {
                log.error("listRPSDevice session  is noAuth");
                return ResultUtil.noLogin();
            }
        }
        List<Device> list = userDeviceService.listRPSDevice(loginUser.getId(), param);
        return ResultUtil.success(list);
    }

    /**
     * 查询R的集合
     * @param loginUser  loginUser
     * @param pageParam pageParam
     * @return Result
     */
    @PostMapping(value = "/queryRlist",produces = "application/json; charset=utf-8")
    public Result<Object> queryRlist(@Logined LoginUser loginUser, @RequestBody PageParam pageParam) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        UserBehavior ubr = new UserBehavior();
        UserCondition uc = new UserCondition();
        pageParam.setUserId(loginUser.getId());
        ubr.setUserId(loginUser.getId());
        uc.setUserId(loginUser.getId());
        PageBar<DeviceExtend> pg = null;
        try {
//            DeviceSearchStatus searchStatus = pageParam.getDeviceSearchStatus();
            ubr.setPn(pageParam.getType());
            ubr.setRemark("queryRlist");
            //当其他页面调用该方法时，需要兼容处理myreceiver页面的favorite行为记录
            if(pageParam.getFavorite()==null){
                UserBehavior playoutBehavior = new UserBehavior();
                playoutBehavior.setUserId(loginUser.getId());
                playoutBehavior.setPn("dn");
                playoutBehavior.setRemark("queryRlist");
                UserBehavior newBehavior = userFeignService.queryUserBehavior(playoutBehavior);
                if(newBehavior !=null){
                    String context = newBehavior.getContent();
                    if(StringUtils.isNotBlank(context)){
                        PageParam param = JsonUtil.toObject(context,PageParam.class);
//                        JSONObject object = (JSONObject)JSONUtils.parse(context);
                        pageParam.setFavorite(param.getFavorite());
                        pageParam.setScope(param.getScope());
                    }
                }
            }
            ubr.setContent(JsonUtil.toJsonStr(pageParam));

            ubr.setUpdateTime(System.currentTimeMillis() + "");
            if (StringUtils.isNotBlank(pageParam.getCondition())) {
                uc.setCondition(pageParam.getCondition());
                userConditionService.updataUserCondition(uc);
            }
            //pageParam.setUserId("8a8c96d951320921015133dac5790003");
            if(!"po".equals(pageParam.getPn())){
                userBehaviorService.updataUserBehavior(ubr);
            }
            pg = userDeviceService.getReceiverList(pageParam);
        } catch (Exception ex) {

            log.error("====queryRlist Exception====",ex);

        }
        //get booking user behavior
        UserBehavior behaviorResult;
        if("po".equals(pageParam.getPn())){
            UserBehavior behavior = new UserBehavior();
            behavior.setPn("po");
            behavior.setUserId(loginUser.getId());
            behavior.setRemark("receiver");
            List<UserBehavior> temp = userBehaviorService.queryUserBehaviorByExample(behavior);
            if(temp !=null && temp.size()>0){
                behaviorResult= temp.get(0);
                Device device= userDeviceService.queryDeviceById(behaviorResult.getPeerId());
                if (device !=null && pageParam.getCondition() !=null){
                    if(device.getName().contains(pageParam.getCondition()) || device.getPeerId().contains(pageParam.getCondition())){
                        DeviceExtend deviceExtend = MyUtil.transfromDevice(device);
                        List<DeviceExtend> deviceExtendList = pg.getResultList();
                        List<DeviceExtend> deviceExtendListBehavior = new ArrayList<DeviceExtend>();
                        deviceExtendListBehavior.add(deviceExtend);
                        Long pageNum = pg.getEveryPageNum();
                        int pageNumInt = pageNum.intValue();
                        //移除与用户行为记录重复的数据
                        if (CollectionUtils.isNotEmpty(deviceExtendList)) {
                            for (int i = 0; i < deviceExtendList.size(); i++) {
                                DeviceExtend extend = deviceExtendList.get(i);
                                if (extend.getPeerId().equals(device.getPeerId())) {
                                    deviceExtendList.remove(i);
                                }
                            }
                        }
                        if (deviceExtendList != null && pg.getEveryPageNum() > deviceExtendList.size()) {
                            deviceExtendListBehavior.addAll(deviceExtendList);
                        } else {
                            if (pageNumInt>=2){
                                deviceExtendListBehavior.addAll(deviceExtendList.subList(0, pageNumInt - 2));
                            }
                        }

                        pg.setResultList(deviceExtendListBehavior);
                    }
                }

            }
        }
        return ResultUtil.success(pg);
    }

    /**
     *
     * @param loginUser loginUser
     * @param pageParam pageParam
     * @return Result
     */
    @RequestMapping(value = "/querySourcelistFR")
    public Result<Object> querySourcelistFR(@Logined LoginUser loginUser, @RequestBody PageParam pageParam)  {


        //pageParam.setUserId("8a8c96d951320921015133dac5790003");
        PageBar<Device> allSource = null;
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }else{
            if(!StringUtils.isBlank(loginUser.getId())){
                pageParam.setUserId(loginUser.getId());
            }else{
                return ResultUtil.noLogin();
            }
        }
        try {
            String role = loginUser.getRole();
             allSource =  userDeviceService.getAllDeviceSource(pageParam,role);
        } catch (Exception ex) {

            log.error("====querySourcelistFR Exception====",ex);

        }
        return ResultUtil.success(allSource);
    }

    /**
     *
     * @param loginUser loginUser
     * @param pageParam pageParam
     * @return Result
     */
    @RequestMapping(value = "/querySourcelistFRByPack")
    public Result<Object> querySourcelistFRByPack(@Logined LoginUser loginUser, @RequestBody PageParam pageParam)  {

        Result<Object> allSource = null;
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }else{
            if(!StringUtils.isBlank(loginUser.getId())){
                pageParam.setUserId(loginUser.getId());
            }else{
                return ResultUtil.noLogin();
            }
        }
        try {
            allSource =  userDeviceService.getAllDeviceSourceByPack(pageParam);
        } catch (Exception ex) {
            log.error("====querySourcelistFR Exception====",ex);
        }
        return allSource;
    }


    /**
     *setting -device 界面,查询和R配对的设备信息
     * @param loginUser loginUser
     * @param pageParam pageParam
     * @return Result
     */
    @RequestMapping(value = "/queryPairSourcelistForR")
    public Result<Object> queryPairSourcelistForR(@Logined LoginUser loginUser, @RequestBody PageParam pageParam)  {

        Result<Object> allSource = null;
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }else{
            if(!StringUtils.isBlank(loginUser.getId())){
                pageParam.setUserId(loginUser.getId());
            }else{
                return ResultUtil.noLogin();
            }
        }
        try {
            String role = loginUser.getRole();
            allSource =  userDeviceService.getAllDeviceSourceByUserOrRid(pageParam,role);
        } catch (Exception ex) {
            log.error("====queryPairSourcelistForR Exception====",ex);
        }
        return allSource;
    }


    /**
     * 导出和R绑定的device到excel表格
     * @param session session
     * @param receiverName r的名字
     * @param export export  导出标识符
     * @param peerId peerId  Rid
     * @param condition condition  搜索条件
     * @param response response
     */
    @GetMapping(value = "/exportExcelByRBindDevice")
    public void exportExcelByRBindDevice(@RequestParam(name = "session") String session,@RequestParam(name = "receiverName") String receiverName,@RequestParam(name = "export") boolean export, @RequestParam(name = "peerId") String peerId,@RequestParam(name = "condition") String condition , HttpServletResponse response)  {

        try {
            LoginUser loginUser = (LoginUser) redisUtil.get(LocalConstant.REDIS_LOGIN_USER_KEY + session);
            String userId = loginUser.getId();
            PageParam pageParam = new PageParam();
            pageParam.setUserId(userId);
            pageParam.setExport(export);
            pageParam.setCondition("");
            pageParam.setPeerId(peerId);
            pageParam.setReceiverName(receiverName);
            String role = loginUser.getRole();
            userDeviceService.extracted(pageParam, response,role);
        } catch (Exception ex) {

            log.error("====exportExcelByRBindDevice Exception====",ex);

        }

    }


    /**
     * 查询用户下的source
     * @param loginUser loginUser
     * @param pageParam pageParam
     * @return Result
     */
    @RequestMapping(value = "/queryUserSourcelist")
    public Result<Object> queryUserSourcelist(@Logined LoginUser loginUser, @RequestBody PageParam pageParam)  {


        //pageParam.setUserId("8a8c96d951320921015133dac5790003");
        Result<Object> allSource = null;
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }else{
            if(!StringUtils.isBlank(loginUser.getId())){
                pageParam.setUserId(loginUser.getId());
            }else{
                return ResultUtil.noLogin();
            }
        }
        try {
            allSource =  userDeviceService.queryUserSourcelist(pageParam);
        } catch (Exception ex) {
            log.error("====querySourcelistFR Exception====",ex);

        }
        return allSource;
    }

    /**
     *
     * @param loginUser loginUser
     * @return Result
     */
    @RequestMapping(value = "/queryGeoRecordSelection")
    public Result<Object> queryGeoRecordSelection(@Logined LoginUser loginUser)  {


        //pageParam.setUserId("8a8c96d951320921015133dac5790003");
        Result<Object> selection = null;
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        try {
            selection =  userDeviceService.queryGeoRecordSelection();
        } catch (Exception ex) {
            log.error("====querySourcelistFR Exception====",ex);
        }
        return selection;
    }

    /**
     *
     * @param loginUser loginUser
     * @param userDeviceOperation userDeviceOperation
     * @return  Result
     * @throws Exception 编译异常
     */
    @RequestMapping(value = "/favoriteOrLiveDescribe",produces = "application/json; charset=utf-8")
    public Result<Object> addfavorite(@Logined LoginUser loginUser,@RequestBody UserDeviceOperation userDeviceOperation) throws Exception {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        try {
            if(userDeviceOperation != null){
                userDeviceOperation.setUserId(loginUser.getId());
            }
//            else {
//                throw new CommonException(CommonConstants.PARAMETER_ERRPR);
//            }
//            if (StringUtils.isBlank(userDeviceOperation.getPeerId())) {
//                throw new CommonException(CommonConstants.PARAMETER_ERRPR);
//            }
            userDeviceService.updataUserDeviceOperation(userDeviceOperation);
        } catch (Exception ex) {
//            logger.error("====addfavorite error: " + ex.toString());

            log.error("====favoriteOrLiveDescribe Exception====",ex);
            return ResultUtil.error("error");
        }
        return ResultUtil.success();

    }

    /**
     *
     * @param loginUser loginUser
     * @return Result
     * @throws Exception 编译异常
     */
    @RequestMapping("/getCondition")
    public Result<Object> getCondition(@Logined LoginUser loginUser) throws Exception {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        List<String> condition = null;
        try {

            condition = userConditionService.getConditionByUserId(loginUser.getId());
        } catch (Exception ex) {
           ex.printStackTrace();
            log.error("====getCondition Exception====",ex);
        }
        return ResultUtil.success(condition);
    }

    /**
     * 查询receiver
     * @param loginUser loginUser
     * @return Result
     * @throws Exception 编译异常
     */
    @RequestMapping("/queryReceiver")
    public Result<Object> queryReceiver(@Logined LoginUser loginUser) throws Exception {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        PageBar<DeviceExtend> pf = null;
        try {
            String contition = "{\"condition\":\"f24701d737c5df98\",\"deviceSearchStatus\":{\"live\":true,\"null\":false,\"offline\":true,\"online\":true,\"sort\":false,\"status\":\"1320\",\"statusList\":[\"1\",\"3\",\"2\",\"0\"]},\"favorite\":\"0\",\"language\":\"zh-CN\",\"pageNum\":1,\"pageSize\":15,\"scope\":\"1\",\"type\":\"dn\",\"userId\":\"8a8c96d951320921015133dac5790003\"}";
            UserBehavior userBehavior=  new UserBehavior();
            userBehavior.setContent(contition);
             pf = userDeviceService.queryReceiver(userBehavior,loginUser.getId());
        } catch (Exception ex) {

            log.error("====queryReceiver Exception====",ex);

        }
        return ResultUtil.success(pf);
    }


}
